package com.example.Servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "NumServlet", value = "/NumServlet")
public class NumServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 设置响应头（禁止缓存，防止验证码过期）
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        // 2. 设置响应类型为图片
        resp.setContentType("image/jpeg");

        // 3. 生成验证码图片（宽100，高30）
        int width = 100;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 4. 绘制背景（白色）
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 5. 绘制边框（灰色）
        g.setColor(Color.GRAY);
        g.drawRect(0, 0, width - 1, height - 1);

        // 6. 生成随机验证码（4位字母数字混合）
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder checkCode = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            // 随机选一个字符
            int index = random.nextInt(base.length());
            char c = base.charAt(index);
            checkCode.append(c);
            // 绘制字符（随机颜色、随机位置，防止机器识别）
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            g.setFont(new Font("Arial", Font.BOLD, 18));
            g.drawString(String.valueOf(c), 20 * i + 10, 20);
        }

        // 7. 绘制干扰线（5条，防止机器识别）
        for (int i = 0; i < 5; i++) {
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            g.drawLine(random.nextInt(width), random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        }

        // 8. 保存验证码到ServletContext（供RegisterServlet验证）
        ServletContext application = req.getServletContext();
        application.setAttribute("checkNum", checkCode.toString());
        System.out.println("生成的验证码：" + checkCode.toString());

        // 9. 输出图片到前端
        ImageIO.write(image, "jpeg", resp.getOutputStream());
        // 关闭资源
        g.dispose();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}